package org.pwwong.scalautils.property

import org.pwwong.scalautils.event._
import org.pwwong.scalautils.signals.{BindableSignal,ConstantSignal,Signal}

object Prop {
  def apply[T](_value:T):Prop[T] = new Prop[T](_value)
  def apply[T](_value:Signal[_<:T]):Prop[T] = new Prop[T](_value)
}

class Prop[T](_boundTo:Signal[_<:T]) extends BindableSignal[T](_boundTo) {  
  def this(initValue:T) = this(ConstantSignal(initValue))
  protected[this] var curValue:T = boundTo().asInstanceOf[T] 
  
  override def apply():T = curValue
  
  protected def setter[U>:T](newValue:U){
    if(newValue != curValue){
      curValue = newValue.asInstanceOf[T]
      onChange.fire(curValue)
    }
  }
  
  override protected def bind { setter(boundTo()); boundTo.onChange(this){ setter(_) } }
  
  def <=>(other:Prop[T]) = {
    this <= other
    other <= this
    this
  }
}
